package com.atguigu.smsservice.controller;


import com.atguigu.commonutils.R;
import com.atguigu.smsservice.service.Smsservice;
import com.atguigu.smsservice.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Api(description = "短息发送 ")
@RestController
@RequestMapping("/edusms/sms")
public class SmsApiController {
    @Resource
    private Smsservice smsservice;
    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @ApiOperation(value = "短信发送")
    @GetMapping("send/{phone}")
    public R send(@PathVariable String phone){
        //查询是否发送过验证码
        String rPhone = redisTemplate.opsForValue().get(phone);
        if (rPhone!=null){
            return R.ok();
        }
        //生成四位随机验证码
        String code = RandomUtil.getFourBitRandom();
        //发送验证码
        HashMap<String, String> map = new HashMap<>();
        map.put("code",code);
        boolean isSend = smsservice.sendSmsPhone(phone,map);
        //存入redis
        if (isSend){
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else {
            return R.error();
        }
    }
}
